

from flask import render_template, redirect, url_for, flash, session
from flask_login import login_required, current_user
from app import db
from app.models import User, Student, Major
from app.forms import NameForm, EditForm
from app.models import admin_required
from . import main

# 创建管理员账户（仅用于开发测试）
@main.route('/create_admin')
def create_admin():
    # 检查是否已存在管理员账户
    admin_user = User.query.filter_by(username='admin').first()
    if admin_user:
        flash('管理员账户已存在')
        return redirect(url_for('main.index'))
    
    # 创建管理员账户
    admin = User(username='admin')
    admin.set_password('admin123')  # 默认密码
    admin.role = 'admin'
    db.session.add(admin)
    db.session.commit()
    
    flash('管理员账户已创建，用户名：admin，密码：admin123')
    return redirect(url_for('main.index'))

@main.route("/",methods=['GET','POST'])
def index():
    studs = Student.query.all()
    majors = Major.query.all() # 查询所有专业
    return render_template('index.html',studs=studs, majors=majors) 

@main.route("/new",methods=['GET','POST'])
@admin_required
def new_stud():
    form = NameForm()
    # 动态填充选项：(value, label) 
    form.major.choices = [(m.id, m.major_name) for m in Major.query.order_by('major_name').all()]
    if form.validate_on_submit():
        id = form.id.data
        name = form.name.data
        # 通过ID获取选择的 Major 对象
        major_obj = Major.query.get(form.major.data)
        newstud = Student(id=id, name=name, age=18, major=major_obj) # 使用正确的字段名
        db.session.add(newstud)
        db.session.commit() 
        flash("a new student record is saved") 
        return redirect(url_for('main.index')) 
    return render_template("new_stud.html",form=form)

@main.route("/major/add")
def major_add():
    m1 = Major(major_name='计算机科学与技术')
    m2 = Major(major_name='软件工程')
    m3 = Major(major_name='信息管理与信息系统')
    db.session.add_all([m1,m2,m3])
    db.session.commit()
    return "专业添加成功"

@main.route("/edit/<int:stu_id>",methods=["GET","POST"])
@admin_required
def edit_stud(stu_id):
    form=EditForm()
    stud = Student.query.get(stu_id)
    # 同样需要动态填充选项
    form.major.choices = [(m.id, m.major_name) for m in Major.query.order_by('major_name').all()]
    if form.validate_on_submit():
        stud.id=form.id.data
        stud.name = form.name.data
        stud.major = Major.query.get(form.major.data) # 更新关联
        db.session.commit() 
        flash('The record is updated') 
        return redirect(url_for('main.index'))
    form.id.data=stud.id
    form.name.data = stud.name
    # 页面加载时，设置下拉框的默认选中项
    if stud.major:
        form.major.data = stud.major_id
    return render_template('edit_stud.html',form=form) # 注意使用修复后的模板名

@main.route('/delete/<int:stud_id>')
@admin_required
def del_stud(stud_id):
    stud = Student.query.get(stud_id)
    if stud:
        db.session.delete(stud)
        db.session.commit()
        flash('学生记录已删除')
    return redirect(url_for('main.index'))

@main.route('/hello',methods=['GET','POST'])
def hello2():
    form = NameForm()
    if form.validate_on_submit():
        oldname = session.get('name')
        if oldname is not None and oldname != form.name.data:
            flash('您的姓名已经更新成功！')
        session['name'] = form.name.data
        return redirect(url_for('hello2'))
    return render_template('user.html',form = form,name = session.get('name'))

@main.route("/major/<int:major_id>")
def filter_by_major(major_id):
    # 找到被点击的专业
    major = Major.query.get_or_404(major_id)
    # 使用 'major' 关系的反向查询 'students'
    studs = major.students.all()
    # 复用 index2.html 模板，但只传入筛选后的学生
    majors = Major.query.all() # 筛选页面也需要专业列表
    return render_template('index.html', studs=studs, majors=majors)

@main.route("/major_information/<major_name>")
def major_information(major_name):
    return render_template("major_information.html", major_name = major_name)
